package com.hz.friends.fragment.contacts;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVGeoPoint;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.hz.friends.activity.GroupInfoActivity;
import com.hz.friends.activity.MaintabsActivity;
import com.hz.friends.activity.R;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.chat.GroupChatActivity;
import com.hz.friends.group.CreateGroupActivity;
import com.hz.friends.serverrequest.ALCCPEngine;
import com.hz.friends.serverrequest.ALCCPEngine.ALGroupType;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.MLog;
import com.hz.friends.utils.UtilTools;

public class GroupContacts {
	private Context mcontext;
	private PullToRefreshListView grouplistview;
	private String TAG = this.getClass().getSimpleName();
	private GrouplistAdpter groupadpter;
	private AQuery aq;

	public GroupContacts(PullToRefreshListView grouplistview, Context mcontext) {
		this.mcontext = mcontext;
		this.grouplistview = grouplistview;
		init();
		initViews();
		initEvents();
		uploadGroupList();
	}

	private void init() {
		aq = new AQuery(mcontext);
	}
	
	private void initViews(){
		if(groupadpter == null)
		 groupadpter = new GrouplistAdpter();
	    grouplistview.setAdapter(groupadpter);
	}

	private void initEvents() {
		grouplistview.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {

			}

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
//				onRefresh();
				groupadpter.clearData();
				groupadpter.notifyDataSetChanged();
				uploadGroupList();
			}
		});
		grouplistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
              
                
			}
		});
	}
	
	
	public void loadData(){
		initViews();
		initEvents();
	}
	
	//用户进入过的群
	private void uploadGroupList(){
		ALCCPEngine.defauleEngine().getGroupListOfEnter(AVUser.getCurrentUser(), new CallBack() {
			
			@Override
			public void done(Object object, AVException avexception) {
				MLog.i(TAG, "uploadGroupList avexception:" + avexception
						+ "  object:" + object);
				grouplistview.onRefreshComplete();
				if (avexception == null) {
					List<AVObject> data = (List<AVObject>) object;
					groupadpter.setData(data);
					groupadpter.notifyDataSetChanged();
				} else {
					avexception.printStackTrace();
//					((MaintabsActivity) mcontext).showSysToast("请求错误");
				}

			}
		});
	}
	
	class GrouplistAdpter extends BaseAdapter {
        private List<AVObject> listdata = new ArrayList<AVObject>();
		
		@Override
		public int getCount() {
			return listdata.size();
		}
		
		public void setData(List<AVObject> data){
			if(data == null){
				data = new ArrayList<AVObject>();
			}
			this.listdata = data;
		}
 
		
		public void clearData(){
			this.listdata.clear();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
 
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = LayoutInflater.from(mcontext).inflate(
					R.layout.adpter_groupcontacts, null);
			final AVObject itemobj = listdata.get(position);
			final String name = itemobj.getString("name");
			String heardUrl = itemobj.getString("coverURL");
			int peoplenum = itemobj.getInt("numberOfMember");
			int roomtype = itemobj.getInt("type");
//			AVGeoPoint mgeopoint = new AVGeoPoint( 39.90248f, 116.2381f);
			AVGeoPoint groupgeopoint = itemobj.getAVGeoPoint("location");
			 Date groupgeopointdate = itemobj.getCreatedAt();

			
			 final ImageView  imv_groupheard = (ImageView)view.findViewById(R.id.imv_groupheard);
			TextView  txv_groupname = (TextView)view.findViewById(R.id.txv_groupname);
			TextView  txv_distancekm = (TextView)view.findViewById(R.id.txv_distancekm);
			TextView  txv_timeafter = (TextView)view.findViewById(R.id.txv_timeafter);
			TextView  txv_groupnum = (TextView)view.findViewById(R.id.txv_groupnum);
			TextView  txv_groupmsg = (TextView)view.findViewById(R.id.txv_groupmsg);
			TextView  txv_grouptype = (TextView)view.findViewById(R.id.txv_grouptype);
			LinearLayout  layout_chat = (LinearLayout)view.findViewById(R.id.layout_chat);
 
			txv_groupname.setText(name);
			txv_groupnum.setText(String.valueOf(peoplenum));
			txv_groupmsg.setText("0");
			setDistance(groupgeopoint,txv_distancekm);
			if(groupgeopointdate != null){
				txv_timeafter.setText(UtilTools.getdurtionTimeFormat(groupgeopointdate, new Date()));
			}else{
				txv_timeafter.setText("no time");
			}
			if(roomtype == ALGroupType.ALGroupTypeOfBusiness.get_value()){
				txv_grouptype.setText("Business");
			}else if(roomtype == ALGroupType.ALGroupTypeOfFood.get_value()){
				txv_grouptype.setText("Food");
			}else if(roomtype == ALGroupType.ALGroupTypeOfNews.get_value()){
				txv_grouptype.setText("News");
			}else if(roomtype == ALGroupType.ALGroupTypeOfChat.get_value()){
				txv_grouptype.setText("Chat");
			}else if(roomtype == ALGroupType.ALGroupTypeOfEntertainMent.get_value()) {
				txv_grouptype.setText("Entertainment");
			}
			
			// default image
			final int width = DensityUtil.dip2px(mcontext, 90);
			Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
			Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(
					mcontext, crclebitmap, width, 1, "#eeeeee");
			imv_groupheard.setImageBitmap(crclestrokebitmap);
			 
			aq.id(imv_groupheard).image(heardUrl,true,true,width,0,new BitmapAjaxCallback(){
				@Override
				protected void callback(String url, ImageView iv, Bitmap bm,
						AjaxStatus status) {
					super.callback(url, iv, bm, status);
					Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(mcontext,
							bm, width, 1, "#eeeeee");
					imv_groupheard.setImageBitmap(mbitmap);
				}
			});
//
//			aq.ajax(heardurl, Bitmap.class, new AjaxCallback<Bitmap>() {
//				@Override
//				public void callback(String url, Bitmap bitmap,
//						AjaxStatus status) {
//					Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(mcontext,
//							bitmap, width, 1, "#eeeeee");
//					holder.imv_heard.setImageBitmap(mbitmap);
//				}
//			});
			
			//聊天室资料
			imv_groupheard.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
		             CustomApplication.getInstance().currgroup = itemobj;
					Intent groupintent = new Intent(mcontext, CreateGroupActivity.class);
					groupintent.putExtra("activitytype", 2);
					mcontext.startActivity(groupintent);
				}
			});
			
			//进入聊天室
			layout_chat.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
		             CustomApplication.getInstance().currgroup = itemobj;
						Intent intent = new Intent(mcontext,GroupChatActivity.class);
						intent.putExtra("titlename", name);
						intent.putExtra("isGroup", true);
						mcontext.startActivity(intent);
				}
			});
			return view;
		}

		
		private void setDistance(AVGeoPoint togeopoint,TextView txv) {
			AVGeoPoint mgeopoint = AVUser.getCurrentUser().getAVGeoPoint("location");
			if(mgeopoint == null || togeopoint == null){
				txv.setText("unknow");
				return;
			}
			double distan = mgeopoint.distanceInKilometersTo(togeopoint);
			  DecimalFormat  df = new DecimalFormat("#.##");
				double km = distan/1000;
			   txv.setText(df.format(km)+" km");
			
		}
	}

}
